import 'package:flutter/cupertino.dart';
import 'package:flutter_demo/pages/404.dart';
import 'package:flutter_demo/pages/component_page/component_page.dart';
import 'package:flutter_demo/pages/home/Home.dart';
import 'package:flutter_demo/pages/home/home_details/home_details.dart';
import 'package:flutter_demo/pages/splash/splash_page.dart';
import 'package:flutter_demo/pages/user/user.dart';
import 'package:flutter_demo/routers/router_paths.dart';
import 'package:go_router/go_router.dart';

class GoRouters {
  GoRouters._();
  // 无动画页面过渡
  static Page<dynamic> _noAnimationPage(
    BuildContext context,
    GoRouterState state,
    Widget child,
  ) {
    return CustomTransitionPage(
      key: state.pageKey,
      child: child,
      transitionsBuilder:
          (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) {
            return FadeTransition(opacity: animation, child: child);
          },
      transitionDuration: Duration.zero,
    );
  }

  /// 路由列表
  static final List<GoRoute> _routers = [
    GoRoute(
      path: RouterPaths.splash,
      name: RouterPaths.splash,
      builder: (_, _) => const SplashPage(),
    ),
    GoRoute(
      path: RouterPaths.home,
      name: RouterPaths.home,
      pageBuilder: (ctx, state) => _noAnimationPage(ctx, state, const Home()),
      routes: [
        GoRoute(
          path: RouterPaths.homeDetail,
          name: RouterPaths.homeDetail,
          pageBuilder: (context, state) => CustomTransitionPage(
            key: state.pageKey,
            child: const HomeDetails(),
            transitionDuration: const Duration(milliseconds: 300),
            transitionsBuilder:
                (context, animation, secondaryAnimation, child) {
                  return FadeTransition(opacity: animation, child: child);
                },
          ),
        ),
      ],
    ),
    GoRoute(
      path: RouterPaths.component,
      name: RouterPaths.component,
      pageBuilder: (ctx, state) =>
          _noAnimationPage(ctx, state, ComponentPage()),
    ),
    GoRoute(
      path: RouterPaths.user,
      name: RouterPaths.user,
      pageBuilder: (ctx, state) => _noAnimationPage(ctx, state, const User()),
    ),

    GoRoute(
      path: RouterPaths.error,
      name: RouterPaths.error,
      builder: (_, _) => const ErrorPage(),
    ),
  ];

  /// 路由实例
  static final GoRouter router = GoRouter(
    routes: _routers,
    initialLocation: RouterPaths.splash,
    errorPageBuilder: (context, state) =>
        _noAnimationPage(context, state, ErrorPage()),

    ///路由守卫
    redirect: (context, state) {
      print("路由守卫打印语句");
      return null;
    },
    debugLogDiagnostics: true,
  );
}
